/*
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi non lorem
 * porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. Etiam sed turpis ac
 * ipsum condimentum fringilla. Maecenas magna. Proin dapibus sapien vel ante. Aliquam erat
 * volutpat. Pellentesque sagittis ligula eget metus. Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.mrd.gtimpframe.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.mrd.base.Jqgrid;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.business.action.AttachmentAction;
import com.mrd.gtimp.business.entity.Attachment;
import com.mrd.gtimp.business.service.AttachmentBiz;
import com.mrd.gtimpframe.entity.BizProtocolConfirm;
import com.mrd.gtimpframe.entity.Dictionary;
import com.mrd.gtimpframe.entity.GenProtocol;
import com.mrd.gtimpframe.entity.GenProtocolFee;
import com.mrd.gtimpframe.entity.GenProtocolProp;
import com.mrd.gtimpframe.entity.GenProtocolUnite;
import com.mrd.gtimpframe.repository.BizProtocolConfirmMapper;
import com.mrd.gtimpframe.repository.CompanyMapper;
import com.mrd.gtimpframe.repository.GenProtocolMapper;
import com.mrd.gtimpframe.repository.GenProtocolUniteMapper;
import com.mrd.gtimpframe.service.DictionaryService;
import com.mrd.gtimpframe.service.ProtocolFeeService;
import com.mrd.gtimpframe.service.ProtocolPropService;
import com.mrd.gtimpframe.service.ProtocolService;
import com.mrd.gtimpframe.vo.GenProtocolUniteVO;
import com.mrd.redis.JedisClientClusterImpl;
import com.mrd.util.LoginUtil;
import com.mrd.util.StringUtils;

/**
 * Created by dengdc on 2017/8/1.
 */
@Service
public class ProtocolServiceImpl implements ProtocolService {
  @Resource
  private GenProtocolMapper genProtocolMapper;
  @Resource
  private ProtocolPropService protocolPropService;
  @Resource
  private ProtocolFeeService protocolFeeService;
  @Resource
  private DictionaryService dictionaryService;
  @Resource
  private BizProtocolConfirmMapper bizProtocolConfirmMapper;
  @Resource
  private GenProtocolUniteMapper genProtocolUniteMapper;
  @Resource
  private AttachmentAction attachmentAction;
  @Resource
  private AttachmentBiz attachmentBiz;
  @Resource
  private CompanyMapper companyMapper;
  @Resource
  private JedisClientClusterImpl redisClusterClient;
  @Resource
  private PlatformFeeServiceImpl platformFeeService;

  /**
   * 保存或更新协议
   *
   * @param unite 协议
   * @param file 附件
   */
  @Override
  @org.springframework.transaction.annotation.Transactional
  public Result saveOrUpdateProtocolUnite(GenProtocolUnite unite, MultipartFile file) {
    if (unite.getEftimeEnd().before(unite.getEftimeStart())) {
      return Result.newFailInstance("结束时间应晚于开始时间");
    }

    String uniteId = unite.getId();
    String supplierId = unite.getSupplierId();
    if (StringUtils.isNotEmpty(uniteId)) {
      unite.setMtime(new Date());
      unite.setModifier(LoginUtil.getLoginAccount());
      genProtocolUniteMapper.updateByPrimaryKeySelective(unite);
    } else {
      unite.setCtime(new Date());
      unite.setCreator(LoginUtil.getLoginAccount());
      unite.setStatus(GenProtocolUnite.CRAFT);
      unite.setId(StringUtils.getUUID());
      genProtocolUniteMapper.insert(unite);
    }
    int count = genProtocolUniteMapper.countByIdAndSupplierId(uniteId, supplierId);
    uniteId = unite.getId();
    if (count == 0) {
      genProtocolMapper.updateSupplierIdByUniteId(unite.getSupplierId(), uniteId);
    }
    if (file != null) {
      attachmentBiz.deleteOfferAttachementByBillNos(uniteId);
      attachmentAction.doUpload(uniteId, "offer", file, null);
    }
    return Result.newSuccessInstance("已保存", uniteId);
  }

  /**
   * 保存或更新协议 数据来自editProtocol.jsp
   */
  @Override
  @Transactional
  public Result saveOrUpdateProtocolFromEditPage() {
    Map<String, String[]> parameterMap = HttpUtils.getRequest().getParameterMap();
    Map<String, Object> beParseMap = new HashMap<>();
    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
      beParseMap.put(entry.getKey(), entry.getValue());
    }
    JSONObject jsonObject = new JSONObject(beParseMap);
    String id = jsonObject.getJSONArray("id").getString(0);
    String name = jsonObject.getJSONArray("name").getString(0);
    String uniteId = jsonObject.getJSONArray("uniteId").getString(0);
    String bizType = jsonObject.getJSONArray("bizType").getString(0);
    String feeType = jsonObject.getJSONArray("feeType").getString(0);
    String dntType = jsonObject.getJSONArray("dntType").getString(0);
    String countRule = jsonObject.getJSONArray("countRule").getString(0);
    String ieType = jsonObject.getJSONArray("ieType").getString(0);
    BigDecimal startCount = jsonObject.getJSONArray("startCount").getBigDecimal(0);
    BigDecimal unitPrice = jsonObject.getJSONArray("unitPrice").getBigDecimal(0);
    BigDecimal capPrice = jsonObject.getJSONArray("capPrice").getBigDecimal(0);
    BigDecimal unitPriceOut = jsonObject.getJSONArray("unitPriceOut").getBigDecimal(0);
    BigDecimal capPriceOut = jsonObject.getJSONArray("capPriceOut").getBigDecimal(0);
    String descript = jsonObject.getJSONArray("descript").getString(0);

    // 保存协议
    GenProtocol genProtocol = buildProtocol(id, name, uniteId, descript);
    saveProtocol(genProtocol);

    // 保存协议属性
    List<GenProtocolProp> protocolProps =
        buildProtocolProps(genProtocol.getId(), bizType, feeType, countRule, ieType, dntType);
    protocolPropService.batchSaveOrUpdate(protocolProps);

    // 保存协议费用
    buildAndSaveFee(genProtocol.getId(), startCount, BigDecimal.ZERO, unitPrice, capPrice,
        BigDecimal.ZERO, unitPriceOut, capPriceOut);
    return Result.newSuccessInstance("已保存");
  }

  /**
   * 构造协议
   *
   * @param name 名称
   * @param uniteId 供应商ID
   * @param descript 描述
   */
  private GenProtocol buildProtocol(String id, String name, String uniteId, String descript) {
    GenProtocol genProtocol = new GenProtocol();
    if (StringUtils.isNotEmpty(id)) {
      genProtocol.setId(id);
    }
    genProtocol.setName(name);
    genProtocol.setUniteId(uniteId);
    genProtocol.setDescript(descript);
    genProtocol.setSupplierId(genProtocolUniteMapper.selectByPrimaryKey(uniteId).getSupplierId());

    return genProtocol;
  }

  /**
   * 构造协议属性
   *
   * @param protocolId 协议ID
   * @param types 类型ID，字典组ID
   */
  private List<GenProtocolProp> buildProtocolProps(String protocolId, String... types) {
    List<GenProtocolProp> props = new ArrayList<>();
    for (String type : types) {
      GenProtocolProp prop = new GenProtocolProp();
      prop.setPropDtId(type);
      prop.setStatus(GenProtocolProp.EFFECTIVE);
      prop.setProtocolId(protocolId);
      prop.setCreateTime(new Date());
      prop.setCreator(LoginUtil.getLoginAccount());
      props.add(prop);
    }
    return props;
  }

  /**
   * 构建协议费用
   *
   * @param startCount 起算数量
   * @param startPrice 起步价
   * @param unitPrice 单价
   * @param capPrice 封顶价
   */
  @Transactional
  public void buildAndSaveFee(String protocolId, BigDecimal startCount, BigDecimal startPrice,
      BigDecimal unitPrice, BigDecimal capPrice, BigDecimal startPriceOut, BigDecimal unitPriceOut,
      BigDecimal capPriceOut) {
    List<GenProtocolFee> fees = protocolFeeService.selectByProtocolId(protocolId);
    boolean[] updatedInAndOut = {false, false};
    for (GenProtocolFee fee : fees) {
      if ("0".equals(fee.getIeType())) {
        fillFeePropsValue(startCount, startPrice, unitPrice, capPrice, fee);
        updatedInAndOut[0] = true;
      } else {
        fillFeePropsValue(startCount, startPriceOut, unitPriceOut, capPriceOut, fee);
        updatedInAndOut[1] = true;
      }
      protocolFeeService.updateByPrimaryKey(fee);
    }
    for (int i = 0; i < updatedInAndOut.length; i++) {
      boolean updated = updatedInAndOut[i];
      if (i == 0 && !updated) {
        GenProtocolFee feeIn = getGenProtocolFee(protocolId, startCount, startPrice, unitPrice,
            capPrice, "0", "CUSTOMER");
        protocolFeeService.insertSelective(feeIn);
      }
      if (i == 1 && !updated) {
        GenProtocolFee feeOut = getGenProtocolFee(protocolId, startCount, startPriceOut,
            unitPriceOut, capPriceOut, "1", "SUPPLIER");
        protocolFeeService.insertSelective(feeOut);
      }
    }
  }

  private GenProtocolFee getGenProtocolFee(String protocolId, BigDecimal startCount,
      BigDecimal startPrice, BigDecimal unitPrice, BigDecimal capPrice, String ieType,
      String customer) {
    GenProtocolFee fee = new GenProtocolFee();
    fee.setId(StringUtils.getUUID());
    fee.setStartCount(startCount);
    fee.setStartPrice(startPrice);
    fee.setUnitPrice(unitPrice);
    fee.setCapPrice(capPrice);
    fee.setIeType(ieType);
    fee.setPayRole(customer);
    fee.setStatus(GenProtocolFee.EFFECTIVE);
    fee.setCreateTime(new Date());
    fee.setCreator(LoginUtil.getLoginAccount());
    fee.setProtocolId(protocolId);
    return fee;
  }

  private void fillFeePropsValue(BigDecimal startCount, BigDecimal startPrice, BigDecimal unitPrice,
      BigDecimal capPrice, GenProtocolFee fee) {
    fee.setStartCount(startCount);
    fee.setStartPrice(startPrice);
    fee.setUnitPrice(unitPrice);
    fee.setCapPrice(capPrice);
    fee.setModifyTime(new Date());
    fee.setModifier(LoginUtil.getLoginAccount());
  }

  /**
   * 保存协议
   *
   * @param protocol 协议
   */
  @Override
  public void saveProtocol(GenProtocol protocol) {
    boolean updateModel = true;
    if (StringUtils.isEmpty(protocol.getId())) {
      protocol.setId(StringUtils.getUUID());
      protocol.setCreator(LoginUtil.getLoginAccount());
      protocol.setCreateTime(new Date());
      protocol.setStatus(GenProtocol.CRAFT);
      updateModel = false;
    } else {
      protocol.setModifier(LoginUtil.getLoginAccount());
      protocol.setModifyTime(new Date());
    }

    if (updateModel) {
      genProtocolMapper.updateByPrimaryKeySelective(protocol);
    } else {
      genProtocolMapper.insertSelective(protocol);
    }
  }

  /**
   * 管理页面数据
   */
  @Override
  public Page uniteManageViewData(Jqgrid jqgrid) {
    jqgrid.pageWithMybatis();
    List<GenProtocolUnite> unites = genProtocolUniteMapper.selectByMap(jqgrid.getFilterMap());
    List<GenProtocolUniteVO> uniteVOList = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(unites)) {
      List<String> uniteIds =
          unites.stream().map(GenProtocolUnite::getId).collect(Collectors.toList());
      List<Attachment> attachments = attachmentBiz.findByBillNos(uniteIds);
      for (GenProtocolUnite unite : unites) {
        for (Attachment atta : attachments) {
          if (unite.getId().equals(atta.getBill_no())) {
            unite.setFile(atta);
            break;
          }
        }
      }
      // 注入提交人\提交时间\确认人\确认时间
      List<String> confirmStatus = new ArrayList<>();
      confirmStatus.add("0");
      confirmStatus.add("1");
      List<BizProtocolConfirm> confirms =
          bizProtocolConfirmMapper.selectByUniteIdInAndStatusIn(uniteIds, confirmStatus);
      for (GenProtocolUnite unite : unites) {
        GenProtocolUniteVO vo = new GenProtocolUniteVO();
        try {
          BeanUtils.copyProperties(vo, unite);
          uniteVOList.add(vo);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      for (BizProtocolConfirm confirm : confirms) {
        for (GenProtocolUniteVO vo : uniteVOList) {
          if (vo.getId().equals(confirm.getProtocolUniteId())) {
            vo.setSubmitor(confirm.getCreator());
            vo.setSubmitTime(confirm.getCreateTime());
            vo.setConfirmer(confirm.getModifier());
            vo.setConfirmTime(confirm.getModifiyTime());
          }
        }
      }
    }
    return jqgrid.pageResult(uniteVOList);
  }


  /**
   * 供应商确认报价页面数据
   */
  @Override
  public Page uniteSupViewData(Jqgrid jqgrid) {
    jqgrid.addRule(new SearchRule("supplierId", SearchRuleOption.eq,
        LoginUtil.getLoginUser().getCompany().getId()));
    if (jqgrid.getFilterMap().get("status") == null) {
      jqgrid.addRule(
          new SearchRule("status", SearchRuleOption.in, new String[] {"1", "2", "3", "4"}));
    }
    return uniteManageViewData(jqgrid);
  }

  /**
   * 管理页面数据
   */
  @Override
  public Page manageViewData(Jqgrid jqgrid, String uniteId) {
    jqgrid.pageWithMybatis();
    Map<String, Object> params = jqgrid.getFilterMap();
    if (StringUtils.isEmpty(uniteId)) {
      return null;
    }
    params.put("uniteId", uniteId);
    List<String> protocolIds = genProtocolMapper.selectIdByUniteMap(params);

    // 本段代码可以在上线后删除
    // boolean needFix = false;
    // if (CollectionUtils.isEmpty(protocolIds)) {
    //
    // params.remove("uniteId");
    // GenProtocolUnite unite = genProtocolUniteMapper.selectByPrimaryKey(uniteId);
    // params.put("supplierId", unite.getSupplierId());
    // jqgrid.pageWithMybatis();
    // protocolIds = genProtocolMapper.selectIdByMapAndUniteIdIsNull(params);
    // needFix = true;
    // }

    if (CollectionUtils.isNotEmpty(protocolIds)) {
      jqgrid.sortWithMybatis();
      List<GenProtocol> protocols = genProtocolMapper.selectByPrimaryKeyList(protocolIds);
      // if (needFix) {
      // //本段代码可以在上线后删除
      // for (GenProtocol protocol : protocols) {
      // protocol.setUniteId(uniteId);
      // }
      // genProtocolMapper.batchUpdateByPrimaryKeySelective(protocols);
      // }
      List<Map<String, Object>> voMapList = new ArrayList<>();
      PageInfo<Map<String, Object>> protocolPageInfo = new PageInfo<>(voMapList);
      for (GenProtocol protocol : protocols) {
        voMapList.add(buildListMap(protocol));
      }
      return new PageImpl(voMapList, jqgrid.getPage(), protocolPageInfo.getTotal());
    }
    return null;
  }


  /**
   * 查询编辑协议报价页面所需要的数据
   */
  @Override
  public Map<String, Object> findForEditPage(String id) {
    return buildEditMap(genProtocolMapper.selectByIdAndFeeIeType(id));
  }

  @Override
  public JSONObject findUniteForEdit(String id) {
    GenProtocolUnite unite = genProtocolUniteMapper.selectByPrimaryKeyExtend(id);
    if (unite != null) {
      List<Attachment> attas =
          attachmentBiz.findByBillNos(Collections.singletonList(unite.getId()));
      if (CollectionUtils.isNotEmpty(attas)) {
        unite.setFile(attas.get(0));
      }
    }
    String jsonString = JSONObject.toJSONString(unite);
    JSONObject jsonObject = JSON.parseObject(jsonString);
    if (jsonObject != null) {
      jsonObject.put("control_supplierId_dropdown", unite.getSupplierName());
    }
    return jsonObject;
  }

  /**
   * 将报价发送到供应商进行确认
   *
   * @param uniteId 协议ID
   */
  public Result sendUniteToSupplier(String uniteId) {
    if (StringUtils.isEmpty(uniteId)) {
      return Result.newFailInstance("包含错误的参数");
    }
    GenProtocolUnite unite = genProtocolUniteMapper.selectByPrimaryKey(uniteId);
    if (unite == null) {
      return Result.newFailInstance("未找到协议，本次操作取消。");
    }
    if (!GenProtocolUnite.CRAFT.equals(unite.getStatus())) {
      return Result.newFailInstance("非草稿不能发送，本次操作取消。");
    }
    if (bizProtocolConfirmMapper.countByUniteIdAndIsNotStatus(uniteId,
        BizProtocolConfirm.UNVALID) != 0) {
      return Result.newFailInstance("此协议已经被发送，本次操作取消。");
    }

    BizProtocolConfirm protocolConfirm = new BizProtocolConfirm();
    protocolConfirm.setId(StringUtils.getUUID());
    protocolConfirm.setSupId(unite.getSupplierId());
    protocolConfirm.setProtocolUniteId(uniteId);
    protocolConfirm.setCreateTime(new Date());
    protocolConfirm.setCreator(LoginUtil.getLoginAccount());
    protocolConfirm.setStartTime(unite.getEftimeStart());
    protocolConfirm.setEndTime(unite.getEftimeEnd());
    protocolConfirm.setStatus(BizProtocolConfirm.TO_BE_CONFIRM);
    bizProtocolConfirmMapper.insert(protocolConfirm);

    unite.setStatus(GenProtocolUnite.WAIT_CONFIRM);
    genProtocolUniteMapper.updateByPrimaryKeySelective(unite);

    return Result.newSuccessInstance("已发送");
  }

  @Override
  public Result cancelSendUniteToSupplier(String uniteId) {
    if (StringUtils.isEmpty(uniteId)) {
      return Result.newFailInstance("包含错误的参数");
    }
    GenProtocolUnite unite = genProtocolUniteMapper.selectByPrimaryKey(uniteId);
    if (unite == null) {
      return Result.newFailInstance("未找到协议，本次操作取消。");
    }
    BizProtocolConfirm confirm = bizProtocolConfirmMapper.selectByUniteIdAndStatus(uniteId,
        BizProtocolConfirm.TO_BE_CONFIRM);
    if (confirm == null) {
      return Result.newFailInstance("未找到可以撤回的记录，本次操作取消。");
    }
    confirm.setStatus(BizProtocolConfirm.UNVALID);
    confirm.setModifier(LoginUtil.getLoginAccount());
    confirm.setModifiyTime(new Date());
    bizProtocolConfirmMapper.updateByPrimaryKeySelective(confirm);

    unite.setStatus(GenProtocolUnite.CRAFT);
    genProtocolUniteMapper.updateByPrimaryKeySelective(unite);

    return Result.newSuccessInstance("已撤回");
  }

  @Override
  @org.springframework.transaction.annotation.Transactional
  public void updateAllUniteToEctStatus() {
    List<String> statusList = new ArrayList<>();
    statusList.add("1");
    statusList.add("3");
    List<GenProtocolUnite> unites = genProtocolUniteMapper.selectByStatusIn(statusList);
    // 生效的协议
    List<GenProtocolUnite> eftUnites = new ArrayList<>();
    // 待生效的协议
    List<GenProtocolUnite> wtUnites = new ArrayList<>();
    for (GenProtocolUnite unite : unites) {
      if (GenProtocolUnite.EFFECTIVE.equals(unite.getStatus())) {
        eftUnites.add(unite);
      } else {
        wtUnites.add(unite);
      }
    }

    Date now = new Date();
    // 用于过滤的map，主要用于找到需要生效的待生效协议
    Map<String, GenProtocolUnite> wtEftUniteMap = new HashMap<>();
    // 待更新集合
    List<GenProtocolUnite> wtModifyList = new ArrayList<>();
    for (GenProtocolUnite wtUnite : wtUnites) {
      String supComId = wtUnite.getSupplierId();
      GenProtocolUnite wtEftUnite = wtEftUniteMap.get(supComId);
      if (now.after(wtUnite.getEftimeStart())) {
        // 开始生效时间早于当前时间，说明协议可以生效
        // 但是由于同一时间只能一个协议生效，所以要找到最合适的协议
        if (wtEftUnite == null || wtUnite.getEftimeStart().after(wtEftUnite.getEftimeStart())) {
          wtEftUnite = wtUnite;
          wtEftUnite.setStatus(GenProtocolUnite.EFFECTIVE);
          wtEftUniteMap.put(supComId, wtEftUnite);
          continue;
        }
      }
      if (now.after(wtUnite.getEftimeEnd())) {
        wtUnite.setStatus(GenProtocolUnite.INVALID);
        wtModifyList.add(wtUnite);
      }
    }

    wtModifyList.addAll(wtEftUniteMap.values());

    // 找到应结束的协议
    for (GenProtocolUnite eftUnite : eftUnites) {
      if (now.after(eftUnite.getEftimeEnd())
          || wtEftUniteMap.get(eftUnite.getSupplierId()) != null) {
        eftUnite.setStatus(GenProtocolUnite.INVALID);
        wtModifyList.add(eftUnite);
      }
    }

    // 统一更新，减少与数据库的交互
    if (CollectionUtils.isNotEmpty(wtModifyList)) {
      genProtocolUniteMapper.batchUpdate(wtModifyList);
    }
    platformFeeService.updateStatusByTime();
    // 优化 清空协议报价缓存（han）

    // 优化 申报口岸供应商缓存（han）
    redisClusterClient.delKeys("protocolCompany_*");
  }

  @Override
  @Cacheable(value = "protocolCompany",
      key = "'protocolCompany_'.concat(#isExport).concat('_').concat(#isCCI)")
  public List<Map<String, Object>> getHaveEftProtocolCompany(boolean isExport, boolean isCCI) {
    List<String> keyList = new ArrayList<>();
    keyList.add(isExport ? "exp" : "imp");
    if (isCCI) {
      keyList.add("protocol_biz_cci");
      keyList.add("protocol_biz_cci_online");
    } else {
      keyList.add("protocol_biz_declaration");
      keyList.add("protocol_biz_baojian");
    }
    List<String> comIdList = new ArrayList<>(genProtocolUniteMapper
        .selectComIdByStatusInAndContainsPropKeys(Collections.singletonList("1"), keyList));
    return companyMapper.selectByPrimaryKeyIn(comIdList);
  }

  /**
   * 构建list页面使用的数据集
   *
   * @param protocol 协议
   */
  private Map<String, Object> buildListMap(GenProtocol protocol) {
    SimpleDateFormat yyyy_MM_ddFormat = new SimpleDateFormat("yyyy-MM-dd");
    Map<String, Object> map = new HashMap<>();
    map.put("id", protocol.getId());
    map.put("name", protocol.getName());
    map.put("supplierName", protocol.getSupplierName());
    map.put("status", tanslateStatus(protocol.getStatus()));
    String eftTimeStr = "";
    if (protocol.getEffectTimeStart() != null) {
      eftTimeStr += yyyy_MM_ddFormat.format(protocol.getEffectTimeStart());
    }
    eftTimeStr += " -- ";
    if (protocol.getEffectTimeEnd() != null) {
      eftTimeStr += yyyy_MM_ddFormat.format(protocol.getEffectTimeEnd());
    }
    map.put("effectiveTime", eftTimeStr);
    map.put("descript", protocol.getDescript());

    List<GenProtocolFee> fees = protocol.getFees();
    if (CollectionUtils.isNotEmpty(fees)) {
      for (GenProtocolFee fee : fees) {
        map.put("startCount", fee.getStartCount());
        if ("1".equals(fee.getIeType())) {
          // map.put("startPriceOut", fee.getStartPrice());
          map.put("unitPriceOut", fee.getUnitPrice());
          map.put("capPriceOut", fee.getCapPrice());
        } else {
          // map.put("startPriceIn", fee.getStartPrice());
          map.put("unitPriceIn", fee.getUnitPrice());
          map.put("capPriceIn", fee.getCapPrice());
        }
      }
    }

    List<GenProtocolProp> props = protocol.getProps();
    if (CollectionUtils.isNotEmpty(props)) {
      List<String> dtIds = new ArrayList<>();
      for (GenProtocolProp prop : props) {
        dtIds.add(prop.getPropDtId());
      }
      List<Dictionary> dictionaries =
          dictionaryService.selectByPrimaryKeyArray(dtIds.toArray(new String[0]));
      for (Dictionary dt : dictionaries) {
        String dtCode = dt.getGroupCode();
        switch (dtCode) {
          case "protocol_biz_type": // 业务类型
            map.put("bizType", dt.getDictionaryName());
            break;
          case "protocol_fee_type": // 费用类型
            map.put("feeType", dt.getDictionaryName());
            break;
          case "protocol_count_fee_rule": // 计费规则
            map.put("countRule", dt.getDictionaryName());
            break;
          case "ie_type": // 进出口
            map.put("ieType", dt.getDictionaryName());
            break;
          case "direct_transit_type": // 直转类型
            map.put("dntType", dt.getDictionaryName());
            break;
          default:
        }
      }
    }
    return map;
  }

  private String tanslateStatus(String status) {
    if (StringUtils.isEmpty(status)) {
      return "";
    }
    switch (status) {
      case "0":
        return "草稿";
      case "1":
        return "生效";
      case "2":
        return "待生效";
      case "3":
        return "结束";
      case "4":
        return "被驳回";
    }

    return null;
  }

  /**
   * 构建edit页面使用的数据集
   *
   * @param protocol 协议
   */
  private Map<String, Object> buildEditMap(GenProtocol protocol) {
    SimpleDateFormat yyyy_MM_ddFormat = new SimpleDateFormat("yyyy-MM-dd");
    Map<String, Object> map = new HashMap<>();
    map.put("id", protocol.getId());
    map.put("name", protocol.getName());
    map.put("supComId", protocol.getSupplierId());
    map.put("control_supComId_dropdown", protocol.getSupplierName());
    Date effectTimeStart = protocol.getEffectTimeStart();
    if (effectTimeStart != null) {
      map.put("effectTimeStart", yyyy_MM_ddFormat.format(effectTimeStart));
    }
    Date effectTimeEnd = protocol.getEffectTimeEnd();
    if (effectTimeEnd != null) {
      map.put("effectTimeEnd", yyyy_MM_ddFormat.format(effectTimeEnd));
    }
    map.put("descript", protocol.getDescript());

    List<GenProtocolFee> fees = protocol.getFees();
    if (CollectionUtils.isNotEmpty(fees)) {
      for (GenProtocolFee fee : fees) {
        map.put("startCount", fee.getStartCount());
        if ("0".equals(fee.getIeType())) {
          // map.put("startPrice", fee.getStartPrice());
          map.put("unitPrice", fee.getUnitPrice());
          map.put("capPrice", fee.getCapPrice());
        } else {
          // map.put("startPriceOut", fee.getStartPrice());
          map.put("unitPriceOut", fee.getUnitPrice());
          map.put("capPriceOut", fee.getCapPrice());
        }
      }
    }

    List<GenProtocolProp> props = protocol.getProps();
    if (CollectionUtils.isNotEmpty(props)) {
      List<String> dtIds = new ArrayList<>();
      for (GenProtocolProp prop : props) {
        dtIds.add(prop.getPropDtId());
      }
      List<Dictionary> dictionaries =
          dictionaryService.selectByPrimaryKeyArray(dtIds.toArray(new String[0]));
      for (Dictionary dt : dictionaries) {
        String dtCode = dt.getGroupCode();
        switch (dtCode) {
          case "protocol_biz_type": // 业务类型
            map.put("bizType", dt.getId());
            map.put("control_bizType_dropdown", dt.getDictionaryName());
            break;
          case "protocol_fee_type": // 费用类型
            map.put("feeType", dt.getId());
            map.put("control_feeType_dropdown", dt.getDictionaryName());
            break;
          case "protocol_count_fee_rule": // 计费规则
            map.put("countRule", dt.getId());
            map.put("control_countRule_dropdown", dt.getDictionaryName());
            break;
          case "ie_type": // 进出口
            map.put("ieType", dt.getId());
            map.put("control_ieType_dropdown", dt.getDictionaryName());
            break;
          case "direct_transit_type": // 直转类型
            map.put("dntType", dt.getId());
            map.put("control_dntType_dropdown", dt.getDictionaryName());
            break;
          default:
        }
      }
    }
    return map;
  }
}
